<template>
    <div class="add-banner-box">

        <el-form style="max-width: 460px" :model="data" :rules="rules" ref="ruleFormRef">
            <div style="margin: 20px" />
            <el-form-item prop="img">
                <el-input class="w-50 m-2" placeholder="请输入图片地址"  v-model="data.img" />
            </el-form-item>

            <el-form-item prop="link">
                <el-input class="w-50 m-2" placeholder="请输入连接"  v-model="data.link"
                    />
            </el-form-item>

            <el-form-item prop="alt">
                <el-input class="w-50 m-2" placeholder="请输入描述（提升）"  v-model="data.alt"                     />
            </el-form-item>

            <el-form-item>                
                <el-button type="primary" @click="addBanner(ruleFormRef)">添加轮播图</el-button>
                <el-button type="primary" @click="cancel">取消</el-button>
            </el-form-item>
        </el-form>

    </div>
</template>

<script setup lang="ts">
import {  reactive, ref, } from 'vue';
import { ElMessageBox, ElMessage} from "element-plus";
import type {FormInstance} from "element-plus";
import type {IAddBanner} from "@/mytype";
import {addBannerApi} from "@/api/banner"

// 声明事件：
const emit = defineEmits<{
    (event: 'hide'): void,
    (event:"ok"):void
}>()

// 定义数据
const data = reactive<IAddBanner>({
    img: "",
    link: "",
    alt:""
})

// 表单验证规则
const rules = reactive({
    img: [
        { required: true, message: '请输入图片路径', trigger: 'blur' }
    ]
})

// 定义ref
const ruleFormRef = ref<FormInstance>()

// 添加轮播图数据
function addBanner(formEl: FormInstance | undefined) {
    // 1、判断用户的输入（非空判断，正则判断）
    console.log("ruleFormRef", ruleFormRef);

    if (!formEl) return;

    formEl.validate((valid, fields) => {
        if (valid) {
            addBannerApi(data)
           .then((data:any)=>{
                if(data.code==="200"){
                    ElMessageBox({
                        title:"提示",
                        message:"添加成功"
                    })
                    emit("ok");
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })

    
}

// 隐藏窗口
function cancel(){
    // 触发事件
    emit("hide");
}

</script>

<style scoped>
.add-banner-box {
    background-color:gray;
    width: 500px;
    height: 300px;
    /* border:5px solid red; */
}

.el-form {
    background-color:gray;
    width: 100%;
    height: 100%;
    padding: 20px;
}
</style>